package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"prod-sys-repo/cache"
	"prod-sys-repo/models"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	content := c.PostForm("content")
	if name == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不为空",
		})
		return
	}
	tx := models.DB.Begin()
	data := models.Product{
		Name:    name,
		Content: content,
	}
	err := tx.Create(&data).Error
	if err != nil {
		tx.Rollback()
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	redis_key := "error_id_" + strconv.Itoa(int(data.ID))
	var product models.Product
	models.DB.Where("id = ?", data.ID).Create(&product)
	JsonData, _ := json.Marshal(product)
	cache.Rdb.Set(cache.Ctx, redis_key, JsonData, time.Hour*2)
	tx.Commit()

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func ProductType(c *gin.Context) {
	pid, _ := strconv.Atoi(c.PostForm("pid"))
	tid, _ := strconv.Atoi(c.PostForm("tid"))

	data := models.ProductType{
		Pid: pid,
		Tid: tid,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	var product []models.Product
	models.DB.Find(&product)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": product,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var product models.Product
	models.DB.Where("id = ?", id).First(&product)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询详情成功",
		"data": product,
	})
	return
}

func DownLoad(c *gin.Context) {

}
